package cn.school.demo.ui.register

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import cn.school.demo.MainViewModel
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentStudentRegisterBinding
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.mylhyl.circledialog.CircleDialog

class RegisterStudentFragment : Fragment() {

    private lateinit var viewModel: RegisterViewModel
    private lateinit var binding: FragmentStudentRegisterBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this).get(RegisterViewModel::class.java)
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_student_register, container, false)
        binding.vm = viewModel
        binding.view = this
        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.unbind()
    }

    private fun init() {
        MyApplication.systemBarSetting(MyApplication.DARK, requireActivity())
        //view
        val array_colleges = MainViewModel().colleges
        val _adapter_colleges: ArrayAdapter<String> = ArrayAdapter(
            this.requireActivity(),
            R.layout.support_simple_spinner_dropdown_item,
            array_colleges
        )

        var array_major: Array<String> = MainViewModel().getMajor("经济学院")
        var _adapter_major: ArrayAdapter<String> = getAdapter("经济学院")

        val array_age: Array<String> = MainViewModel().getAge()
        val _adapter_age = ArrayAdapter(
            this.requireActivity(),
            R.layout.support_simple_spinner_dropdown_item,
            array_age
        )

        val array_class = arrayOf("1", "2", "3")

        with(binding.registerCollegeSpinner) {
            adapter = _adapter_colleges
            setSelection(0)
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    LogUtils.i("选中了${array_colleges[position]}")
                    viewModel.setCollage(array_colleges[position])
                    array_major = MainViewModel().getMajor(array_colleges[position])
                    _adapter_major = getAdapter(array_colleges[position])
                    binding.registerMajorSpinner.adapter = _adapter_major
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                    ToastUtils.showShort("not implemented")
                }
            }
        }
        with(binding.registerMajorSpinner) {
            adapter = _adapter_major
            setSelection(0)
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    LogUtils.e("选中了${array_major[position]}")
                    viewModel.setMajor(array_major[position])
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                    ToastUtils.showShort("not implemented")
                }
            }
        }
        with(binding.registerAgeSpinner) {
            adapter = _adapter_age
            setSelection(0)
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    LogUtils.e("选中了${array_age[position]}")
                    viewModel.setGrade(array_age[position])
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                    ToastUtils.showShort("not implemented")
                }
            }
        }
        with(binding.registerClassSpinner) {
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    LogUtils.e("选中了${array_class[position]}")
                    viewModel.setTeam(array_class[position])
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                    ToastUtils.showShort("not implemented")
                }
            }
        }
    }

    private fun getAdapter(college_name: String): ArrayAdapter<String> = ArrayAdapter(
        this.requireActivity(),
        R.layout.support_simple_spinner_dropdown_item,
        MainViewModel().getMajor(college_name)
    )


    fun registerStudentGetCodeButtonOnClick() {
        val toastText = viewModel.getVerificationCodeDetection()
        toastText?.let { ToastUtils.showShort(toastText) }
            ?: let {
                viewModel.getCodeText(binding.registerPhoneStudentEditView.text.toString())
                MyApplication.animationCountdown(
                    binding.registerStudentGetCodeButton,
                    null,
                    "RegisterByStudent"
                )
            }
    }

    fun registerStudentRegisterButtonOnClick() {
        LogUtils.e(viewModel.user.value)
        val toastText = viewModel.getStudentRegisterDetection()
        toastText?.let { ToastUtils.showShort(toastText) } ?: let {
            //发送注册信息
            viewModel.setIdentity("学生")
            LogUtils.d(viewModel.user.value)
            if (binding.registerCodeStudentEditView.text.toString() == viewModel.getCode.value) {
                viewModel.getResult(viewModel.user.value!!)
                viewModel.result.observe(viewLifecycleOwner) {
                    LogUtils.d("我变化了啊！")
                    when (viewModel.result.value?.success) {
                        true -> {
                            MyApplication.apply {
                                user = viewModel.user.value
                                navigateThing["SetLove"] = "Article to SetLove"
                                goto(
                                    R.id.action_RegisterByStudent_to_SetLove,
                                    findNavController(),
                                    parentFragmentManager
                                )
                            }
                        }
                        else -> CircleDialog.Builder()
                            .setText(viewModel.result.value!!.message)
                            .setNegative("确定", null)
                            .show(parentFragmentManager)
                    }
                }
            } else {
                CircleDialog.Builder().setText("验证码错误！").setNegative("确定") {
                    viewModel.setCode("")
                }.show(parentFragmentManager)
            }

        }
    }

    fun setId() = viewModel.setId(binding.registerIDStudentEditView.text.toString())
    fun setName() = viewModel.setName(binding.registerNameStudentEditView.text.toString())
    fun setPwd() = viewModel.setPwd(binding.registerPasswordStudentEditView.text.toString())
    fun setPhone() =
        viewModel.setPhone(binding.registerPhoneStudentEditView.text.toString())

    fun setRePwd() =
        viewModel.setRePwd(binding.registerRePasswordStudentEditView.text.toString())

    fun setCode() = viewModel.setCode(binding.registerCodeStudentEditView.text.toString())
}